package com.lyp.qczp.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.lyp.qczp.dao.Kaotidao;
import com.lyp.qczp.entity.Kaoti;

@Service
public class KaotiServiceImp implements KaotiService{

	@Autowired
	private Kaotidao kaotidao;
	
	@Override
	public int save(Kaoti kaoti) {
		// TODO Auto-generated method stub
		Kaoti save = kaotidao.save(kaoti);
		if (save!=null) {
			return 1;
		}
		return 0;
	}

	@Override
	public int deleteById(Integer kId) {
		kaotidao.deleteById(kId);
		return 1;
	}

	@Override
	public Map<String, Object> findAll(PageRequest pageable,Kaoti kaoti) {
		Page<Kaoti> findAll = kaotidao.findAll(selectquanpage(kaoti),pageable);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", findAll.getContent());
		map.put("total", findAll.getTotalElements());
		return map;
	}


	//条件查询Specification
		private Specification<Kaoti> selectquanpage(Kaoti kaoti){
			return new Specification<Kaoti>() {

				/**
				 * 
				 */
				private static final long serialVersionUID = 1L;

				@Override
				public Predicate toPredicate(Root<Kaoti> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
					// TODO Auto-generated method stub
					Predicate conjunction = cb.conjunction();
				List<Expression<Boolean>> expressions = conjunction.getExpressions();
					if (kaoti.getKYi()!=null&&kaoti.getKYi()!=0) {
						expressions.add(cb.equal(root.<Integer>get("kYi"), kaoti.getKYi()));
					}
					if (kaoti.getKEr()!=null&&kaoti.getKEr()!=0) {
						expressions.add(cb.equal(root.<Integer>get("kEr"), kaoti.getKEr()));
					}
					
					return conjunction;
				}
			};
		}

		@Override
		public List<Kaoti> findBykEr(Integer kEr) {
			return kaotidao.findBykEr(kEr);
		}
	
	
	
	
	
}
